import axios from "axios";
import { Session, Local } from "@/utils/storage";
import qs from "qs";
let requests  = [];

const service = axios.create({
  timeout: 50000,
  headers: { "Content-Type": "application/json" },
  paramsSerializer: {
    serialize(params) {
      return qs.stringify(params, { allowDots: true });
    },
  },
});

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么 token
    const tokenInfo = Session.get("tokenInfo") || {};
    const access_token = tokenInfo.access_token;
    if (access_token) {
      config.headers["Authorization"] = `Bearer ${access_token}`;
    }

    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const res = response.data;

    if (res.code && res.code !== rescf.codeVal) {
      // `token` 过期或者账号已在别处登录
      if (res.code === 401 || res.code === 4001) {
        Session.clear();
        Local.clear();
        window.location.href = "/"; // 去登录页
      }
      return res;
    } else {
      return res;
    }
  },
  (error) => {
    // 对响应错误做点什么
    if (error.message.indexOf("timeout") != -1) {
      // message && message.error("网络超时");
    } else if (error.message == "Network Error") {
      // message && message.error("网络连接错误");
    } else {
      if (error.response) {
        if (error.response.status === 401) {
          // window.__NUXT_Oidc__.signoutRedirect();
          // window.__NUXT_Oidc__.signinRedirect();
        } else {
          // message && message.error(error.response.statusText);
        }
      } else {
        // message && message.error("接口路径找不到");
      }
    }
    return Promise.reject(error);
  }
);

const getBaseUrl = (prefix) => {
  // console.log(window.ENV_HOST, 'window[prefix || "BASE_URL"]');
  // console.log(import.meta.env, "import.meta.env");
  // return import.meta.env[prefix || "VITE_BASE_URL"];
  console.log(window.__VITE_ENV, 'window.__VITE_ENV')
  return window.__VITE_ENV[prefix || "BASE_URL"];
};

const axiosGo = (config) => {
  // service.defaults.baseURL = env.API_URL;
  const prefix = getBaseUrl(config.prefix);
  const baseurl = prefix;
  console.log(baseurl, "baseurl");
  service.defaults.baseURL = baseurl;
  service.defaults.headers = config.headers;

  return new Promise((resolve, reject) => {
    service(config)
      .then((r) => {
        // axiosGo.requests.push((token) => {
        //   return new Promise((resolve) => {
        //     response.config.headers.authorization = `${token_info.token_type} ${token}`;
        //     resolve(service(response.config)); //执行请求，
        //   });
        // });
        if (!r) return;

        const o = { ...r };
        if (["arraybuffer", "blob"].includes(config.responseType)) {
          resolve(r);
        } else {
          o.code = r[rescf.code];
          o.msg = r[rescf.msg] || r?.msg || "";
          if (o.msg instanceof Object) {
            o.msg = Object.values(o.msg).join("|");
          }
          if (r[rescf.data]) {
            let d = {};
            const rd = r[rescf.data];
           

            if (rd instanceof Array) {
              o.data = r[rescf.data];
            } else {
              if (rd[rescf.dataList]) {
                d.list = rd[rescf.dataList];
                d.pageIndex = rd[rescf.pageIndex];
                d.limit = rd[rescf.limit];
                d.pageCount = rd[rescf.pageCount];
                d.total = rd[rescf.total];
                o.data = d;
              } else {
                o.data = r[rescf.data];
              }
            }
          }
        }
        resolve(o);
      })
      .catch((err) => {
        console.log(err, "---err--");
        if (err.response?.status * 1 === 401) {
          window.location.href = window.location.origin + "/login";
          Session.clear();
        }
        reject(err);

        try {
          useSaveError(err);
        } catch {}
      });
  });
};

axiosGo.requests = [];
axiosGo.addAccessTokenExpiring = () => {
  console.log("reflashToken");
};

export default axiosGo;
